package com.mall.seckill_mall.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class LockUtil {

    @Autowired
    private  RedisTemplate<String, String> redisTemplate;

    public boolean lock(String key, String value, long ttl) {
        Boolean ok = redisTemplate.opsForValue().setIfAbsent(key, value, ttl, TimeUnit.MILLISECONDS);
        return ok != null && ok;
    }

    public  boolean unlock(String key, String value) {
        String v = redisTemplate.opsForValue().get(key);
        if(v != null && v.equals(value)) {
            redisTemplate.delete(key);
            return true;
        }
        return false;
    }
}
